﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using System;

namespace Bookvar.Common
{
    public static class FileUtility
    {
        private static readonly SysImageList imageList = new SysImageList();
        private const string ImageFileNamePattern = @".*\.(png|jpg|bmp|gif|jpeg)$";
        private static string bookvarLocalApplicationFolder;
        public static string BookvarLocalApplicationFolder
        {
            get
            {
				
                if (bookvarLocalApplicationFolder == null)
                {
                    string localApplicationFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                    bookvarLocalApplicationFolder = Path.Combine(localApplicationFolder, "Bookvar");
                }
				EnsureBookvarLocalApplicationFolder();
                
                return bookvarLocalApplicationFolder;
            }
        }
        public static bool IsImage(string fileName)
        {
            return Regex.IsMatch(fileName, ImageFileNamePattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        }

        public static BitmapFrame GetFileIcon(string fileName)
        {
            int index = imageList.IconIndex(fileName, true);
            imageList.ImageListSize = SysImageListSize.ExtraLargeIcons;
            Icon icon = imageList.Icon(index);
            if (icon != null)
            {
                Bitmap bitmap = icon.ToBitmap();
                MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, ImageFormat.Png);
                PngBitmapDecoder decoder =
                    new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
                return decoder.Frames[0];
            }
            return null;
        }

       
        private static void EnsureBookvarLocalApplicationFolder()
        {

            if (!Directory.Exists(bookvarLocalApplicationFolder))
            {
                Directory.CreateDirectory(bookvarLocalApplicationFolder);
            }
        }
    }
}